/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.connector.base.message.model;

import com.alibaba.fastjson2.JSONObject;
import com.je.connector.base.config.InstantConfig;
import com.je.connector.base.connection.Connection;
import com.je.connector.base.connection.channel.NettyChannelSocketChannel;
import com.je.connector.base.exception.ConnectorException;
import com.je.connector.base.exception.ServerException;
import com.je.connector.base.protocol.Command;
import com.je.connector.base.protocol.Packet;
import io.netty.channel.ChannelFutureListener;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 定义基础消息
 *
 * @ProjectName: instant-message
 * @Package: com.connector.base.message.model
 * @ClassName: BaseMessage
 * @Description: 基础消息定义，所有消息都要从此处扩展
 * @Author: LIULJ
 * @Version: 1.0
 * <p>Copyright: Copyright (c) 2018</p>
 */
public abstract class BaseMessage implements Message {

    /**
     * 已经解码
     */
    private static final byte STATUS_DECODED = 1;
    /**
     * 已经编码
     */
    private static final byte STATUS_ENCODED = 2;

    protected static final AtomicInteger ID_SEQ = new AtomicInteger();

    transient protected Packet packet;
    transient protected Connection connection;
    transient private byte status = 0;

    public BaseMessage() {
    }

    public Packet getPacket() {
        return packet;
    }

    public BaseMessage(Packet packet, Connection connection) {
        this.packet = packet;
        this.connection = connection;
    }

    @Override
    public void decodeBody() {
        if ((status & STATUS_DECODED) == 0) {
            status |= STATUS_DECODED;
            if (packet.getBodyLength() > 0) {
                decodeBody0();
            }
        }
    }

    @Override
    public void encodeBody() {
        if ((status & STATUS_ENCODED) == 0) {
            status |= STATUS_ENCODED;
            encodeBody0();
        }
    }

    /**
     * 根据配置进行压缩或加密
     */
    private void encodeBody0() {
        byte[] tmp = encode();
        if (InstantConfig.server.compress) {
            //采用压缩
            throw new ServerException("no support for body compression");
        }
        if (InstantConfig.server.encryption) {
            //采用加密
            throw new ServerException("no support for body encryption");
        }
        packet.setBody(tmp);
    }

    /**
     * 根据配置进行解压缩和解密
     */
    private void decodeBody0() {
        byte[] tmp = packet.getBody();
        if (InstantConfig.server.compress) {
            //采用压缩，进行解压缩
            throw new ServerException("no support for body compression");
        }
        if (InstantConfig.server.encryption) {
            //采用加密，进行解密
            throw new ServerException("no support for body encryption");
        }
        if (tmp.length == 0) {
            throw new ServerException("message decode ex");
        }
        packet.setBody(tmp);


        decode(packet.getBody());
        //释放内存
        packet.setBody(null);
    }

    /**
     * 消息实现的编码
     *
     * @return
     */
    public abstract byte[] encode();

    /**
     * 消息实现的解码
     *
     * @param body
     */
    public abstract void decode(byte[] body);

    @Override
    public Connection getConnection() {
        return connection;
    }

    @Override
    public void channelSend(ChannelFutureListener listener) {
        encodeBody();
        if (connection.getSocketClient() instanceof NettyChannelSocketChannel) {
            connection.channelSend(packet, listener);
        } else {
            throw new ConnectorException("only Netty Channel support this method!");
        }
    }

    @Override
    public void send(String eventName) {
        encodeBody();
        throw new ConnectorException("only SocketIo Client support this method!");
    }

    /**
     * 关闭
     */
    public void close() {
        connection.disConnect();
    }

    /**
     * 构建成功响应
     *
     * @param connection
     * @return
     * @throws Exception
     */
    public static OkMessage buildSuccessResponse(Connection connection) throws Exception {
        JSONObject dataObj = new JSONObject();
        dataObj.put("success", true);
        dataObj.put("msg", "发送成功");
        return new OkMessage(new Packet(Command.OK.cmd, Packet.NORMAL_RESP_TYPE), connection).setType(MessageType.HANDSHAKE_TYPE).setData(dataObj.toJSONString());
    }

    /**
     * 构建失败响应
     *
     * @param connection
     * @return
     */
    public static ErrorMessage buildErrorResponse(Connection connection) {
        JSONObject dataObj = new JSONObject();
        dataObj.put("success", false);
        dataObj.put("msg", "发送失败");
        return new ErrorMessage(new Packet(Command.ERROR.cmd, Packet.NORMAL_RESP_TYPE), connection);
    }
}
